﻿using System;

using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace Scan
{
    public class SysUpdate
    {
        private static NLog.Logger logger = NLog.LogManager.GetLogger("SysUpdate");
        public const string VersionKey = "SysVer";
        public static string UpdatePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\update\\";
        public static string UpdateFileName = "patch.cab";

        /// <summary>
        /// 下载更新包是否成功;
        /// 1:需要更新；2：不需要；3：失败
        /// </summary>
        public static int DownloadResult = 3;
        
        /// <summary>
        /// 下载更新包
        /// </summary>
        /// <returns>返回1:需要更新；2：不需要；3：失败</returns>
        public static int DownloadPatch()
        {
            logger.Debug("DownloadPatch...");

            string path = UpdatePath;
            string fileName = UpdateFileName;

            int ret = 3;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (File.Exists(path + fileName))
                {
                    File.Delete(path + fileName);
                }

                PDAService.PDAService service = Webservice.GetWebservice();

                object oVer = GetRegistryValue(VersionKey);
                string oldVer = (oVer == null) ? "1.0.0.0" : oVer.ToString();
                string newVer = "";
                Byte[] downPatch = service.GetIntallPatch(oldVer, ref newVer);

                // == null 则不需要更新
                if (downPatch != null)
                {
                    byte[] f = ConvertZip.DeCompress(downPatch);
                    FileStream fs = new FileStream(path + fileName, FileMode.OpenOrCreate);
                    fs.Write(f, 0, f.Length);
                    fs.Flush();
                    fs.Close();

                    SetRegistryValue("SysVer", newVer);
                    ret = 1;
                }
                else if (newVer == "N")
                {
                    ret = 2;
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("DownloadPatch()", ex);
            }

            DownloadResult = ret;
            return ret;
        }

        #region
        public static object GetRegistryValue(string key)
        {
            object o = null;
            try
            {
                RegistryKey subkeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ACOSME");
                if (subkeys != null)
                {
                    o = subkeys.GetValue(key);
                }
                subkeys.Close();
            }
            catch (Exception ex)
            {
                logger.ErrorException("GetRegistryValue()", ex);
            }
            return o;
        }

        public static bool SetRegistryValue(string key, object value)
        {
            bool result = false;
            try
            {
                RegistryKey subkeys = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ACOSME");
                if (subkeys != null)
                {
                    subkeys.SetValue(key, value);
                    result = true;
                }
                subkeys.Close();
            }
            catch (Exception ex)
            {
                logger.ErrorException("SetRegistryValue", ex);
            }
            return result;
        }
        #endregion
    }
}
